package com.jingdianjichi.changerecord.impl;


import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.jingdianjichi.changerecord.entity.Dict;
import com.jingdianjichi.changerecord.enums.RedisKeyEnum;
import com.jingdianjichi.changerecord.strategy.DictStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 字典工具类
 *
 * @author Hu_bx
 * @date 9:40 2022/11/11
 **/
@Slf4j
public class DefaultDictImpl implements DictStrategy {
    private final Map<String, List<Dict>> dictMap = MapUtil.newHashMap();

    @Override
    public String getDictByCode(String parentCode, String code) {
        if (StrUtil.isBlank(code)) {
            return null;
        }
        TimeInterval timeInterval = new TimeInterval();
        timeInterval.start();
        List<Dict> dictionaryDtoList = getDictList(parentCode);
        Optional<Dict> first = dictionaryDtoList.stream()
                .filter(dictionaryDto -> dictionaryDto.getCode()
                        .equals(code))
                .findFirst();
        log.debug("常量字段耗时 {},redisKey = {}", timeInterval.intervalMs(), parentCode);
        return first.map(Dict::getValue).orElse(null);
    }

    @Override
    public List<Dict> getDictList(String parentCode) {
        if (ObjUtil.isEmpty(parentCode)) {
            return CollUtil.toList();
        }
        TimeInterval timeInterval = new TimeInterval();
        timeInterval.start();
        String key = RedisKeyEnum.DICT_ALL_KEY.getKey() + parentCode;
        // 内存缓存获取
        // 当涉及循环查询字典，redis还是有点慢的，短时间查询使用内存缓存
        List<Dict> dictList = dictMap.get(key);
        return dictList == null ? CollUtil.toList() : dictList;
    }

    @Override
    public void initDict(List<Dict> dictList) {
        if (ObjUtil.isEmpty(dictList)) {
            return;
        }
        Map<String, List<Dict>> map = CollStreamUtil.groupByKey(dictList, Dict::getParentCode);
        dictMap.putAll(map);
    }
}
